define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxBuildings";

    var fxBuildingsFormHtml = sysPath + "/views/fxBuildingsForm.html";
    var getFxBuildingsController = function () {
        return getServer() + "/fxBuildingss";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
        //initProvinceSelect();
        //initCitySelect();
        //initAreaSelect();
        initYearDate();
        initStructureTypeSelect();
        createFxBuildingsGrid();
    };
    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
    var initProvinceSelect = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "province",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("provinceSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initCitySelect = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("citySelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initAreaSelect = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("areaSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initYearDate = function () {
        $("#yearCondition").datetimepicker({
            //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
            language: "cn",
            //输出格式化
            format: 'yyyy',
            //直接选择‘今天’
            todayBtn: true,
            weekStart: 1,
            // 设置最精确的时间选择视图
            startView: 4,
            //设置最精确的时间选择视图
            minView: 4,
            //高亮当天日期
            todayHighlight: true,
            //选择完毕后自动关闭
            autoclose: true
        });
    };
    var initStructureTypeSelect = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "structureType",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("structureTypeSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initProvinceSelectFrom = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "province",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("province");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initCitySelectFrom = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("city");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initAreaSelectFrom = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("area");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initStructureTypeSelectFrom = function () {
        $.ajax({
            url: getFxBuildingsController() + "/getValidDictItemsByDictCode/" + "structureType",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("structureType");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initYearTimeDate = function () {
        $("#year").datetimepicker({
            //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
            language: "cn",
            //输出格式化
            format: 'yyyy',
            //直接选择‘今天’
            todayBtn: true,
            weekStart: 1,
            // 设置最精确的时间选择视图
            startView: 4,
            //设置最精确的时间选择视图
            minView: 4,
            //高亮当天日期
            todayHighlight: true,
            //选择完毕后自动关闭
            autoclose: true
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createFxBuildingsGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
            $("#yearCondition").val("");
            $("#buildingNameCondition").val("");
            $("#structureTypeSelect").val("");
        });
    };
    var createFxBuildingsGrid = function () {
        $("#fxBuildingsGrid").datagrid({
            url: getFxBuildingsController() + "/queryFxBuildingss",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'province',
                    title: '省',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'buildingName',
                    title: '建筑物名称',
                    width: '12%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxBuildings(\'' + rowData.id + '\');"> ' + rowData.buildingName + ' </a> '
                    }
                },
                {
                    field: 'structureType',
                    title: '结构类型',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'buildingArea',
                    title: '建筑面积',
                    width: '5%',
                    align: 'center',
                },
                {
                    field: 'peopleNumber',
                    title: '人数',
                    width: '5%',
                    align: 'center',
                },
                {
                    field: 'purpose',
                    title: '用途',
                    width: '15%',
                    align: 'center',
                },
                {
                    field: 'floorNumber',
                    title: '层数',
                    width: '5%',
                    align: 'center',
                },
                {
                    field: 'year',
                    title: '年代',
                    width: '10%',
                    align: 'center',
                    sortable: true
                },
                {
                    field: 'currentIntensity',
                    title: '现设防烈度',
                    width: '6.5%',
                    align: 'center',
                    /*formatter: function (value) {
                        if (value == "6") {
                            return 'VI';
                        } else if (value == "7") {
                            return 'VII';
                        } else if (value == "8") {
                            return 'VIII';
                        } else if (value == "9") {
                            return 'IX';
                        } else if (value == "10") {
                            return 'X';
                        }
                    }*/
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxBuildings();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxBuildings();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                year: $("#yearCondition").val(),
                buildingName: $("#buildingNameCondition").val(),
                structureType: $("#structureTypeSelect").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#fxBuildingsForm").validate({
            rules: {
                province: {
                    required: true,
                },
                city: {
                    required: true,
                },
                area: {
                    required: true,
                },
                buildingName: {
                    required: true,
                },
                structureType: {
                    required: true,
                },
                year: {
                    required: true,
                },
            },
            messages: {
                province: {
                    required: "省不允许为空!",
                },
                city: {
                    required: "市不允许为空!",
                },
                area: {
                    required: "区（县）不允许为空!",
                },
                buildingName: {
                    required: "建筑物名称不允许为空!",
                },
                structureType: {
                    required: "结构类型不允许为空!",
                },
                year: {
                    required: "年代不允许为空!",
                },
            }
        });
    };
    var getFxBuildings = function (id) {
        $.ajax({
            url: getFxBuildingsController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("fxBuildingsForm", data);
            }
        });
    };
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
    var addFxBuildings = function () {
        var slidebar = Util.slidebar({
            url: fxBuildingsFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                initcreateProvinceForm();
                // initProvinceSelectFrom();
                // initCitySelectFrom();
                // initAreaSelectFrom();
                initStructureTypeSelectFrom();
                initYearTimeDate();
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxBuildingsForm").valid()) {
                        var data = Tool.serialize("fxBuildingsForm");
                        $.ajax({
                            url: getFxBuildingsController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxBuildingsGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    // 导出
    var exportForm = function () {
        let province = $("#provinceSelect").val();
        let city = $("#citySelect").val();
        let area = $("#areaSelect").val();
        let year = $("#yearCondition").val();
        let buildingName = $("#buildingNameCondition").val();
        let structureType = $("#structureTypeSelect").val();
        window.location.href = getFxBuildingsController() + "/export?province=" + province + "&city=" + city + "&area=" + area + "&year= " + year + " &structureType="
            + structureType + "&buildingName=" + buildingName;
    };
    window._editFxBuildings = function (fxBuildingsId) {
        var slidebar = Util.slidebar({
            url: fxBuildingsFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                // initProvinceSelectFrom();
                // initCitySelectFrom();
                // initAreaSelectFrom();
                initStructureTypeSelectFrom();
                initYearTimeDate();
                formValidator();
                getFxBuildings(fxBuildingsId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxBuildingsForm").valid()) {
                        var data = Tool.serialize("fxBuildingsForm");
                        $.ajax({
                            url: getFxBuildingsController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxBuildingsGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxBuildings = function () {
        var rows = $("#fxBuildingsGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxBuildingsController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxBuildingsGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
